package com.hm.oltu.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hm.common.util.CommonUtil;
import com.hm.oltu.def.CommonDef.OperationStatus;
import com.hm.oltu.model.User;
import com.hm.oltu.service.UserService;
import com.hm.oltu.su.ControllerResult;
import com.hm.oltu.su.PageInfo;
import com.hm.oltu.vo.UserVo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("user")
public class UserController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@RequestMapping("index")
	public String index() {
		return "user/index";
	}

	@RequestMapping("add")
	public String add() {
		return "user/add";
	}

	@RequestMapping(value = "saveAdd", method = RequestMethod.POST)
	public @ResponseBody ResponseEntity<ControllerResult<String>> add(@RequestBody(required = true) UserVo userVo) {
		try {
			if (CommonUtil.isNotEmpty(userService.findByUsername(userVo.getUsername()))) {
				return ControllerResult.failed("当前用户已存在,添加失败");
			}
			User user = userService.createUser(userVo);
			if (CommonUtil.isNotEmpty(user)) {
				return ControllerResult.success(user.getId(), OperationStatus.ADD_SUCCESSFUL);
			}
			return ControllerResult.failed("保存失败");
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}

	@RequestMapping(value = "{userId}", method = RequestMethod.DELETE)
	public @ResponseBody ResponseEntity<ControllerResult<Boolean>> delete(@PathVariable("userId") String userId) {
		try {
			if (CommonUtil.isEmpty(userId)) {
				logger.debug("request param error like this user/{userId}");
				return ControllerResult.failed("request param error like this user/{userId}");
			}
			userService.deleteUser(userId);
			return ControllerResult.success(true, OperationStatus.DELELETE_SUCCESSFUL);
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}

	@RequestMapping("{pageNo}/{pageSize}")
	public @ResponseBody ResponseEntity<ControllerResult<PageInfo<UserVo>>> query(@PathVariable("pageNo") int pageNo,
			@PathVariable("pageSize") int pageSize) {
		try {
			if (CommonUtil.isAnyEmpty(pageNo, pageSize)) {
				log.error("request param error like this user/{pageNo}/{pageSize}");
				return ControllerResult.failed("request param error like this user/{pageNo}/{pageSize}");
			}
			return ControllerResult.success(userService.query(pageNo, pageSize), OperationStatus.QUERY_SUCCESSFUL);
		} catch (Exception e) {
			return ControllerResult.failed(e);
		}
	}
}
